﻿using NRediSearch;
using StackExchange.Redis;

namespace RedisSearchDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6375,defaultDatabase=0");
            IDatabase db = redis.GetDatabase();

            var client = new Client("blog", db);
            client.DropIndex();
            client.CreateIndex(new Schema() // 创建一个索引
                .AddTextField("title", 5.0)  // 文本类型，权重为5.0
                .AddTextField("content", 1.0) // 文本类型，权重为1.0
                .AddTagField("tags", ","), new Client.ConfiguredIndexOptions() // 标签类型，分隔符为逗号
                );

            client.AddDocument(
                // 添加一个文档对象
                new Document("blog:1", new Dictionary<string, RedisValue>
                {
                    { "title", "Hello Redis Search" },
                    { "content", "This is a blog post about Redis Search, a query and full-text search engine for Redis."},
                    { "tags", "redis,search" } // 设置标签字段
                }));

            client.AddDocument(
                // 添加一个文档对象
                new Document("blog:2", new Dictionary<string, RedisValue>
                {
                    { "title", "Redis Base Class" },
                    { "content", "This is a blog post about Redis Search, a query and full-text search engine for Redis."},
                    { "tags", "redis,search" } // 设置标签字段
                }));

            client.AddDocument(
                // 添加一个文档对象
                new Document("blog:3", new Dictionary<string, RedisValue>
                {
                    { "title", "Singing and drawing" },
                    { "content", "This is a blog post about Redis Search, a query and full-text search engine for Redis."},
                    { "tags", "redis,search" } // 设置标签字段
                }));

            var result = client.Search(new Query("Singing")); // 创建一个查询对象
            Console.WriteLine(result.TotalResults); // 打印匹配的文档数量
            foreach (var doc in result.Documents) 
            {
                Console.WriteLine(doc.Id); // 打印文档ID
                Console.WriteLine(doc["title"]); // 打印标题字段
                Console.WriteLine(doc["content"]); // 打印内容字段
                Console.WriteLine(doc["tags"]); // 打印标签字段
            }
            ;
            client.UpdateDocument("blog:1", new Dictionary<string, RedisValue>
            {
                { "title", "Hello RediSearch" },
                { "tags", "redis,search,full-text" },
            });
            ;
            client.DeleteDocument("blog:1");
        }
    }
}
